package com.components.project

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.os.Build
import android.os.Process
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
import android.widget.FrameLayout
import androidx.annotation.Nullable
import com.components.cachewebview.WebViewCacheInterceptorInst
import com.tencent.smtt.export.external.interfaces.*
import com.tencent.smtt.sdk.*


@SuppressLint("ViewConstructor")
class X5WebView(p0: Context, p1: AttributeSet?, url: String) : WebView(p0, p1) {

    private var mUrl = url
    private var mContext: Context = p0
    private var wSettings: WebSettings? = null

    init {
        initWebViewClient()
        initWebChromeClient()
        initWebViewSettings()
    }

    private fun initWebViewSettings() {
        wSettings = this.settings

        wSettings?.allowFileAccess = true
        wSettings?.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        wSettings?.setSupportZoom(true)
        wSettings?.builtInZoomControls = true
        wSettings?.useWideViewPort = true
        wSettings?.setSupportMultipleWindows(true)
        wSettings?.setAppCacheEnabled(true)
        wSettings?.domStorageEnabled = true
        wSettings?.javaScriptEnabled = true
        wSettings?.setGeolocationEnabled(true)
        //优先阻塞图片的加载（http的图片链接加载不出来）,在onPageFinished中去取消阻塞，再重新加载图片
        wSettings?.blockNetworkImage = true
        //允许从任何来源加载内容
        wSettings?.mixedContentMode = MIXED_CONTENT_ALWAYS_ALLOW//（这句不知道有用没，X5里面没有该属性）
        wSettings?.setAppCachePath(mContext.getDir("appcache", 0).path)

        this.loadUrl(mUrl)
//        WebViewCacheInterceptorInst.getInstance()?.loadUrl(mUrl, wSettings.userAgentString)
    }

    private fun initWebViewClient() {
        this.webViewClient = object : WebViewClient() {

            override fun onPageFinished(view: WebView?, url: String?) {
                wSettings?.blockNetworkImage = false//解除阻塞
                //判断哪web是否加载了图片资源
                if (wSettings?.loadsImagesAutomatically != true) {
                    wSettings?.loadsImagesAutomatically = true//设置加载图片资源
                }
                super.onPageFinished(view, url)
            }

            override fun shouldOverrideUrlLoading(
                view: WebView?,
                request: WebResourceRequest
            ): Boolean {
                WebViewCacheInterceptorInst.getInstance()?.loadUrl(view, request.url.toString())
                return true
            }

            override fun shouldOverrideUrlLoading(view: WebView?, url: String): Boolean {
                WebViewCacheInterceptorInst.getInstance()?.loadUrl(view, url)
                return true
            }

            @Nullable
            override fun shouldInterceptRequest(
                view: WebView?,
                request: WebResourceRequest?
            ): WebResourceResponse? {
                return WebViewCacheInterceptorInst.getInstance()?.interceptRequest(request)
            }

            @Nullable
            override fun shouldInterceptRequest(
                view: WebView?,
                url: String
            ): WebResourceResponse? {
                return WebViewCacheInterceptorInst.getInstance()?.interceptRequest(url)
            }

            override fun onLoadResource(view: WebView?, url: String?) {
                super.onLoadResource(view, url)
            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest,
                error: WebResourceError
            ) {
                val code = error.errorCode
                val resp = error.description.toString()
                val url = request.url.toString()
                super.onReceivedError(view, request, error)
            }
        }
    }

    private fun initWebChromeClient() {
        this.webChromeClient = object : WebChromeClient() {

            var myVideoView: View? = null
            var myNormalView: View? = null
            var callback: IX5WebChromeClient.CustomViewCallback? = null

            override fun onJsConfirm(
                p0: WebView?,
                p1: String?,
                p2: String?,
                p3: JsResult?
            ): Boolean {
                return super.onJsConfirm(p0, p1, p2, p3)
            }

            override fun onShowCustomView(p0: View, p1: IX5WebChromeClient.CustomViewCallback) {
                var fl: FrameLayout = this@X5WebView
                val normalView = this@X5WebView.parent as ViewGroup
//                normalView.removeView(fl)
                normalView.addView(p0)
                myVideoView = p0
                myNormalView = fl
                callback = p1
            }

            override fun getVideoLoadingProgressView(): View {
                val frameLayout = FrameLayout(context)
                frameLayout.layoutParams = LayoutParams(
                    LayoutParams.MATCH_PARENT,
                    LayoutParams.MATCH_PARENT
                )
                return frameLayout
            }

            override fun onHideCustomView() {
                callback?.onCustomViewHidden()
                callback = null

                var viewGroup: ViewGroup? = myVideoView?.parent as ViewGroup
                viewGroup?.removeView(myVideoView)
//                viewGroup?.addView(myNormalView)
            }

            override fun onJsAlert(p0: WebView?, p1: String?, p2: String?, p3: JsResult?): Boolean {
                return super.onJsAlert(null, p1, p2, p3)
            }
        }
    }

    override fun drawChild(canvas: Canvas, child: View?, drawingTime: Long): Boolean {
        val ret = super.drawChild(canvas, child, drawingTime)
        canvas.save()
        val paint = Paint()
        paint.color = 0x7fff0000
        paint.textSize = 24f
        paint.isAntiAlias = true
        if (x5WebViewExtension != null) {
            canvas.drawText(
                this.context.packageName + "-pid:"
                        + Process.myPid(), 10f, 50f, paint
            )
            canvas.drawText(
                "X5  Core:" + QbSdk.getTbsVersion(this.context), 10f, 100f, paint
            )
        } else {
            canvas.drawText(
                (this.context.packageName + "-pid:"
                        + Process.myPid()), 10f, 50f, paint
            )
            canvas.drawText("Sys Core", 10f, 100f, paint)
        }
        canvas.drawText(Build.MANUFACTURER, 10f, 150f, paint)
        canvas.drawText(Build.MODEL, 10f, 200f, paint)
        canvas.restore()
        return ret
    }
}